class Snake {
    head: HTMLElement
    bodies: HTMLCollection
    element: HTMLElement

    constructor() {
        this.element = document.getElementById('snake')!
        this.head = document.querySelector('#snake > div')!
        this.bodies = this.element.getElementsByTagName('div')

    }

    get X () {
        return this.head.offsetLeft
    }

    get Y () {
        return this.head.offsetTop
    }

    set X (val: number) {
        if (this.X === val) {
            return
        }

        if (val < 0 || val > 290) {
            throw new Error('蛇撞墙了！')
        }

        if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetLeft === val) {
            // 发生掉头
            if (val < this.X) {
                val = this.X + 10
            } else {
                val = this.X - 10
            }
        }

        this.moveBody()

        this.head.style.left = val + 'px'
        this.checkHeadBody()
    }

    set Y (val: number) {
        if (this.Y === val) {
            return
        }

        if (val < 0 || val > 290) {
            throw new Error('蛇撞墙了！')
        }

        if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetTop === val) {
            // 发生掉头
            if (val < this.Y) {
                val = this.Y + 10
            } else {
                val = this.Y - 10
            }
        }

        this.moveBody()

        this.head.style.top = val + 'px'
        this.checkHeadBody()
    }

    addBody () {
        // 向element中添加一个div
        this.element.insertAdjacentHTML('beforeend', '<div></div>')
    }

    moveBody () {
        for (let i = this.bodies.length - 1; i > 0; i --) {
            const X = (this.bodies[i - 1] as HTMLElement).offsetLeft
            const Y = (this.bodies[i - 1] as HTMLElement).offsetTop

            ;(this.bodies[i] as HTMLElement).style.left = X + 'px'
            ;(this.bodies[i] as HTMLElement).style.top = Y + 'px'
        }
    }

    checkHeadBody () {
        for (let i = 1; i < this.bodies.length; i ++) {
            const bd = this.bodies[i] as HTMLElement
            if (this.X === bd.offsetLeft && this.Y === bd.offsetTop) {
                throw new Error('撞到自己了！')
                break
            }
        }
    }
}

export default Snake